#import "FlutterDeviceUuidPlugin.h"

@implementation FlutterDeviceUuidPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"flutter_device_uuid"
            binaryMessenger:[registrar messenger]];
  FlutterDeviceUuidPlugin* instance = [[FlutterDeviceUuidPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getDeviceUuid" isEqualToString:call.method]) {
      NSString *storeKey;
      if (call.arguments!=nil&&[call.arguments isKindOfClass:NSDictionary.class]) {
          if ([[call.arguments allKeys] containsObject:@"iosStoreKey"]) {
              storeKey = call.arguments[@"iosStoreKey"];
          }
      }
    
      result([FlutterDeviceUuidPlugin getUUIDByKeyChain:storeKey]);
  } else {
      result(FlutterMethodNotImplemented);
  }
}

+ (NSString *)getUUIDByKeyChain:(NSString *)storeKey{
    // 这个key的前缀最好是你的BundleID
    NSString*strUUID = @"";
    
    BOOL save = storeKey!=nil&&[storeKey isKindOfClass:NSString.class]&&storeKey.length>0;
    if (save) {
        strUUID = (NSString*)[self load:storeKey];
    }
    
    //首次执行该方法时，uuid为空
    if([strUUID isEqualToString:@""] || !strUUID) {
        CFUUIDRef uuidRef= CFUUIDCreate(kCFAllocatorDefault);
        strUUID = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault,uuidRef));
        CFRelease(uuidRef);
        //将该uuid保存到keychain
        if (save) {
            [self save:storeKey data:strUUID];
        }
    }
    return strUUID;
}

+ (NSMutableDictionary*)getKeychainQuery:(NSString*)service {
    return[NSMutableDictionary dictionaryWithObjectsAndKeys:
           (id)kSecClassGenericPassword,(id)kSecClass,
           service,(id)kSecAttrService,
           service,(id)kSecAttrAccount,
           (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
           nil];
}
 
+ (void)save:(NSString*)service data:(id)data{
    //Get search dictionary
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef)keychainQuery);
    //Add new object to searchdictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data]forKey:(id)kSecValueData];
    //Add item to keychain with the searchdictionary
    SecItemAdd((CFDictionaryRef)keychainQuery,NULL);
}
 
+ (id)load:(NSString*)service {
    id ret =nil;
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:service];
    //Configure the search setting
    //Since in our simple case we areexpecting only a single attribute to be returned (the password) wecan set the attribute kSecReturnData to kCFBooleanTrue
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData =NULL;
    if(SecItemCopyMatching((CFDictionaryRef)keychainQuery,(CFTypeRef*)&keyData) ==noErr){
        @try{
            ret =[NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData*)keyData];
        }@catch(NSException *e) {
            NSLog(@"Unarchiveof %@ failed: %@",service, e);
        }@finally{
        }
    }
    if(keyData)
        CFRelease(keyData);
    return ret;
}
 
+ (void)deleteKeyData:(NSString*)service {
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}

@end
